package com.manor.dynamic.dialog;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.manor.dynamic.R;
import com.manor.common.Constants;
import com.manor.common.bean.UserBean;
import com.manor.common.dialog.AbsDialogFragment;
import com.manor.common.dialog.ChatFaceDialog;
import com.manor.common.event.DynamicCommentEvent;
import com.manor.common.http.HttpCallback;
import com.manor.common.http.PitUtil;
import com.manor.common.utils.DialogUitl;
import com.manor.common.utils.DpUtil;
import com.manor.common.utils.StringUtil;
import com.manor.common.utils.ToastUtil;
import com.manor.common.utils.WordUtil;
import com.manor.dynamic.activity.AbsDynamicCommentActivity;
import com.manor.dynamic.activity.DynamicDetailsActivity;
import com.manor.dynamic.bean.DynamicCommentBean;
import com.manor.dynamic.http.DynamicHttpConsts;
import com.manor.dynamic.http.DynamicHttpUtil;
import com.manor.im.utils.ImTextRender;
import com.manor.video.utils.VideoTextRender;

import org.greenrobot.eventbus.EventBus;


/**
 * Created by cxf on 2018/12/3.
 * 视频评论输入框
 */

public class DynamicInputDialogFragment extends AbsDialogFragment implements View.OnClickListener,
        ChatFaceDialog.ActionListener {

    private InputMethodManager imm;
    private EditText mInput;
    private boolean mOpenFace;
    private int mOriginHeight;
    private int mFaceHeight;
    private ImageView mCheckBox;
    private ChatFaceDialog mChatFaceDialog;
    private Handler mHandler;
    private String mDynamicId;
    private String mDynamicUid;
    private DynamicCommentBean mDynamicCommentBean;
    private boolean isbq = true;


    @Override
    protected int getLayoutId() {
        return R.layout.dialog_dynamic_input_light;
    }

    @Override
    protected int getDialogStyle() {
        return R.style.dialog2_sd;
    }

    @Override
    protected boolean canCancel() {
        return true;
    }

    @Override
    protected void setWindowAttributes(Window window) {
        window.setWindowAnimations(R.style.bottomToTopAnim);
        WindowManager.LayoutParams params = window.getAttributes();
        params.width = WindowManager.LayoutParams.MATCH_PARENT;
        mOriginHeight = DpUtil.dp2px(48);
        params.height = mOriginHeight;
        params.gravity = Gravity.BOTTOM;
        window.setAttributes(params);
        final Handler hanler = new Handler();
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            public InputMethodManager mInputMethodManager;

            @Override
            public void onDismiss(DialogInterface dialog) {
                hanler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        hideSoftkeyboard();
                    }
                }, 200);

            }
        });
    }

    public void hideSoftkeyboard() {
        try {
            ((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE))
                    .hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
        } catch (NullPointerException e) {

        }
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        mHandler = new Handler();
        mInput = mRootView.findViewById(R.id.input);

        mInput.setOnClickListener(this);
        mInput.setFocusable(true);
        mInput.setFocusableInTouchMode(true);
        mInput.requestFocus();
        mRootView.findViewById(R.id.btn_at).setOnClickListener(this);
        mRootView.findViewById(R.id.btn_voice_input).setOnClickListener(this);
        mCheckBox = mRootView.findViewById(R.id.btn_face);
        mCheckBox.setOnClickListener(this);
        mInput.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEND) {
                    sendComment();
                    return true;
                }
                return false;
            }
        });
        Bundle bundle = getArguments();
        if (bundle != null) {
            mOpenFace = bundle.getBoolean(Constants.VIDEO_FACE_OPEN, false);
            //  mInput.setText(bundle.getString(Constants.VIDEO_COMMENT_MSG));
            mInput.setText(ImTextRender.renderChatMessage(bundle.getString(Constants.VIDEO_COMMENT_MSG)));
            mInput.setSelection(mInput.getText().toString().length());
            mFaceHeight = bundle.getInt(Constants.VIDEO_FACE_HEIGHT, 0);
            mDynamicCommentBean = bundle.getParcelable(Constants.VIDEO_COMMENT_BEAN);
            if (mDynamicCommentBean != null) {
                UserBean replyUserBean = mDynamicCommentBean.getUserBean();//要回复的人
                if (replyUserBean != null) {
                    mInput.setHint(WordUtil.getString(R.string.video_comment_reply) + replyUserBean.getUserNiceName());
                }
            }
        }
        if (mOpenFace) {
            isbq = true;
            if (mCheckBox != null) {
                //     mCheckBox.setChecked(true);
            }
            if (mFaceHeight > 0) {
                changeHeight(mFaceHeight);
                if (mHandler != null) {
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            showFace();
                        }
                    }, 200);
                }
            }
        } else {
            isbq = false;
            if (mHandler != null) {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        showSoftInput();
                    }
                }, 200);
            }
        }
    }


    public void setDynamicInfo(String dynamicId, String dynamicUid) {
        mDynamicId = dynamicId;
        mDynamicUid = dynamicUid;
    }


    private void showSoftInput() {
        //软键盘弹出
        if (imm != null) {
            imm.showSoftInput(mInput, InputMethodManager.SHOW_FORCED);
        }
        if (mInput != null) {
            mInput.requestFocus();
        }
    }

    public void hideSoftInput() {
        if (imm != null) {
            imm.hideSoftInputFromWindow(mInput.getWindowToken(), 0);
        }
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        View v = getActivity().getWindow().peekDecorView();
        if (null != v) {
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }

    }


    @Override
    public void onDestroy() {
        hideSoftInput();
        ((DynamicDetailsActivity) mContext).setTextContext(mInput.getText().toString());

        if (mContext != null) {
            ((AbsDynamicCommentActivity) mContext).releaseVideoInputDialog();
        }
        mContext = null;
        DynamicHttpUtil.cancel(DynamicHttpConsts.DYNAMIC_SET_COMMENTS);
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
        mHandler = null;
        if (mChatFaceDialog != null) {
            mChatFaceDialog.dismiss();
        }
        mChatFaceDialog = null;
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        if (!canClick()) {
            return;
        }
        int i = v.getId();
        if (i == R.id.btn_face) {
            clickFace();
        } else if (i == R.id.input) {
            clickInput();
        } else if (i == R.id.btn_voice_input) {
            clickVoice();
        }
    }


    /**
     * 点击语音
     */
    public void clickVoice() {
        hideSoftInput();
        dismiss();
        ((AbsDynamicCommentActivity) mContext).showVoiceViewHolder(mDynamicId, mDynamicUid, mDynamicCommentBean);
    }


    private void clickInput() {
        hideFace();
        if (mCheckBox != null) {
            isbq = false;
            //    mCheckBox.setChecked(false);
        }
    }

    private void clickFace() {

        //     dismiss();icon_jianpan
        if (!isbq) {
            hideSoftInput();
            if (mHandler != null) {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        isbq = true;
                        mCheckBox.setImageResource(R.mipmap.icon_jianpan);
                        showFace();
                    }
                }, 200);
            }
        } else {
            hideFace();
            showSoftInput();
            isbq = false;
            mCheckBox.setImageResource(R.mipmap.icon_chat_face);
        }
    }

    private void showFace() {
        if (mFaceHeight > 0) {
            changeHeight(mFaceHeight);
            View faceView = ((AbsDynamicCommentActivity) mContext).getFaceView();
            if (faceView != null) {
                mChatFaceDialog = new ChatFaceDialog(mRootView, faceView, false, DynamicInputDialogFragment.this);
                mChatFaceDialog.show();
            }
        }
    }

    private void hideFace() {
        if (mChatFaceDialog != null) {
            mChatFaceDialog.dismiss();
        }
    }

    /**
     * 改变高度
     */
    private void changeHeight(int deltaHeight) {
        Dialog dialog = getDialog();
        if (dialog == null) {
            return;
        }
        Window window = dialog.getWindow();
        if (window == null) {
            return;
        }
        WindowManager.LayoutParams params = window.getAttributes();
        params.height = mOriginHeight + deltaHeight;
        window.setAttributes(params);
    }

    @Override
    public void onFaceDialogDismiss() {
        changeHeight(0);
        mChatFaceDialog = null;
    }

    /**
     * 发表评论
     */
    public void sendComment() {

        if (TextUtils.isEmpty(mDynamicId) || TextUtils.isEmpty(mDynamicUid) || mInput == null || !canClick()) {
            return;
        }
        String content = mInput.getText().toString().trim();
        if (TextUtils.isEmpty(content)) {
            ToastUtil.show(R.string.content_empty);
            return;
        }
        String toUid = mDynamicUid;
        String commentId = "0";
        String parentId = "0";
        if (mDynamicCommentBean != null) {
            toUid = mDynamicCommentBean.getUid();
            commentId = mDynamicCommentBean.getCommentId();
            parentId = mDynamicCommentBean.getId();
        }
        DynamicHttpUtil.setComment(toUid, mDynamicId, content, commentId, parentId, "", new HttpCallback() {
            @Override
            public void onSuccess(int code, String msg, String info) {
                if (code == 0 && StringUtil.isNotEmpty(info)) {
                    if (mInput != null) {
                        mInput.setText("");
                    }
                    String result = PitUtil.strGetFirst(info);

                    JSONObject obj = JSON.parseObject(result);
                    String commentNum = obj.getString("comments");
                    EventBus.getDefault().post(new DynamicCommentEvent(mDynamicId, commentNum));
                    ToastUtil.show(msg);
                    dismiss();
                    ((AbsDynamicCommentActivity) mContext).refreshComment();
                } else {
                    ToastUtil.show(msg);
                }
            }

            @Override
            public boolean showLoadingDialog() {
                return true;
            }

            @Override
            public Dialog createLoadingDialog() {
                return DialogUitl.loadingDialog(mContext);
            }
        });
    }

    /**
     * 点击表情上面的删除按钮
     */
    public void onFaceDeleteClick() {
        if (mInput != null) {
            int selection = mInput.getSelectionStart();
            String text = mInput.getText().toString();
            if (selection > 0) {
                String text2 = text.substring(selection - 1, selection);
                if ("]".equals(text2)) {
                    int start = text.lastIndexOf("[", selection);
                    if (start >= 0) {
                        mInput.getText().delete(start, selection);
                    } else {
                        mInput.getText().delete(selection - 1, selection);
                    }
                } else {
                    mInput.getText().delete(selection - 1, selection);
                }
            }
        }
    }


    /**
     * 点击表情
     */
    public void onFaceClick(String str, int faceImageRes) {
        if (mInput != null) {
            Editable editable = mInput.getText();
            editable.insert(mInput.getSelectionStart(), VideoTextRender.getFaceImageSpan(str, faceImageRes));
        }
    }


    @Override
    public void onDismiss(DialogInterface dialog) {
        hideSoftInput();
        super.onDismiss(dialog);


    }


}
